package org.summerframework.component.upload.fastdfs.pool;

import org.summerframework.component.upload.fastdfs.FastDFSTemplateFactory;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

import java.io.IOException;

/**
 * 链接创建
 */
class ConnectionFactory extends BasePooledObjectFactory<TrackerServer> {
    private FastDFSTemplateFactory factory;

    ConnectionFactory(FastDFSTemplateFactory templateFactory) {
        this.factory = templateFactory;
    }

    @Override
    public TrackerServer create() throws Exception {
        TrackerClient trackerClient = new TrackerClient(factory.getTrackerGroup());
        return trackerClient.getConnection();
    }

    @Override
    public PooledObject<TrackerServer> wrap(TrackerServer trackerServer) {
        return new DefaultPooledObject<>(trackerServer);
    }

    @Override
    public void destroyObject(PooledObject<TrackerServer> pooledObject) throws Exception {
        if (pooledObject.getObject() != null) {
            pooledObject.getObject().close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<TrackerServer> p) {
        try {
            return ProtoCommon.activeTest(p.getObject().getSocket());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
